package com.wstuo.common.security.dao;

import com.wstuo.common.dao.BaseDAOImplHibernate;
import com.wstuo.common.security.entity.OrganizationInner;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

/**
 * 内部机构DAO.
 * @author will
 */
@SuppressWarnings( "unchecked" )
public class OrganizationInnerDAO
    extends BaseDAOImplHibernate<OrganizationInner>
    implements IOrganizationInnerDAO
{
	
	@Autowired
	private IOrganizationDAO organizationDAO;
	
	
	/**
     * 根据公司编号查找内部机构列表.
     * @param companyNo 公司编号 Long
     * @return 内部机构列表 List<OrganizationInner>
     */
    public List<OrganizationInner> findByCompany( Long companyNo )
    {
        List<OrganizationInner> organizationInners =
            super.getHibernateTemplate(  )
                 .find( " from OrganizationInner orgInner where orgInner.parentOrg.orgNo=" + companyNo +" order by orgInner.orgNo");

        return organizationInners;
    }
    
    
    
    /**
     * 重写SAVE方法.
     * @param entity
     */
     @Override
     public void save(OrganizationInner entity){

     	if(entity.getOrgNo()==null || entity.getOrgNo()==0){
     		entity.setOrgNo(organizationDAO.getLatestOrganizationNo());
     	}else{
     		
     		if(entity.getOrgNo()>organizationDAO.getLatestOrganizationNo()){
     			
     			organizationDAO.setLatesOrganizationNo(entity.getOrgNo());
     		}
     	}
     	
     	super.save(entity);
     	organizationDAO.increment();//自增1.
     }
     
     /**
      * 重写merge方法.
      * @param entity
      * @return OrganizationInner
      */
     @Override
     public OrganizationInner merge(OrganizationInner entity){
    	 	 
    	 if(entity.getOrgNo()!=null){
     		if(entity.getOrgNo()>=organizationDAO.getLatestOrganizationNo()){
     			organizationDAO.setLatesOrganizationNo(entity.getOrgNo()+1);
     		}
     	}else{
     		organizationDAO.increment();//自增1.
   		}
    	 
    	 return super.merge(entity);
     }
    
}
